<template>
	<view class="index-box" :style="{ '--color': vuex_config.themeColor1, '--price': vuex_config.price }">
		<sww-nav-bar title="购物车" v-if="zfbNav"></sww-nav-bar>
		<block v-if="vuex_cart_list.length > 0">
			<view class="data-list">
				<block v-for="(item, index) in vuex_cart_list" :key="index">
					<view class="data-item">
						<view class="data-radio" :class="{ 'data-radio-act': isSelect(item.pk_id) }"
							@click="$onSelect(item.pk_id, item.is_online)">
							<template>
								<u-icon :name="isSelect(item.pk_id) ? 'e730' : 'e72f'" size="34"
									custom-prefix="iconfont" />
							</template>
							<!-- 							<template v-else>
								<u-icon name="e889" size="34" custom-prefix="iconfont" />
							</template> -->
						</view>
						<!-- @click="$toProd({pk_id: item.product_id, prodType: 1})" -->
						<view class="data-img">
							<image @click="onDetail(item.product_id)" style="width: 100%;height: 100%;" class="u-border"
								:src="item.product_img" mode="aspectFill"></image>
							<no-stock v-if="item.is_online <= 0" />
						</view>
						<view class="data-right" @click="onDetail(item.product_id, item.is_online)">
							<view class="title_box">
								<view class="data-title u-line-2 u-font-28">{{ item.product_name }}</view>
								<view class="data-del" @click.stop="$onDelete(item, index)">
									<u-icon name="e74b" size="34" color="#666666" custom-prefix="iconfont"></u-icon>
								</view>
							</view>
							<view class="data-desc" @click.stop="$showSpec(item)">
								<text class="u-line-1 u-m-r-4">{{ item.standard }}</text>
								<u-icon name="arrow-down-fill" size="24" top="1" color="#666666"></u-icon>
							</view>
							<view class="data-bottom">
								<view class="data-price">
									<text class="u-font-24">￥</text>
									<!-- 会员、普通价格 -->
									<text
										class="u-font-32">{{ $price(showVip && item.vip_price ? item.vip_price : item.price) | priceFmt }}</text>
									<text
										class="u-font-24">{{ $price(showVip && item.vip_price ? item.vip_price : item.price) | priceFmt(true) }}</text>
								</view>
								<view @click.stop="">
									<!-- 用view包着是为了防止冒泡 支付宝这垃圾点击会冒泡 -->
									<u-number-box :value="item.num" input-height="44" input-width="60"
										@plus="$numChange($event, 1, item)" @minus="$numChange($event, -1, item)"
										:index="index" :max="item.max_num" :min="item.minimum || 1"
										:disabled-input="true" :long-press="false"></u-number-box>
								</view>
							</view>
						</view>
					</view>
				</block>
			</view>
			<sww-goods-spec v-model="specVisible" :params="stockItem" type="1"></sww-goods-spec>
		</block>
		<block v-else>
			<view class="no-data-box">
				<image class="no-data-img"
					src="http://klwl-file.oss-cn-shenzhen.aliyuncs.com/202104/admin/56759473789623.png"></image>
				<view class="no-data-text u-font-24 c-99">购物车是空的</view>
			</view>
		</block>
		<view class="topic-data-box">
			<view class="topic-data-title">推荐商品</view>
			<sww-prod-list ref="prodListRef" :params="shareParams"></sww-prod-list>
		</view>
		<sww-goods-action :custom-style="`padding-bottom: ${actionPadding}rpx`">
			<view class="sub-bottom">
				<view class="sub-radio-wrap" @click="$onSelectAll">
					<view class="sub-radio" :class="{ 'sub-radio-act': isSelectAll }">
						<u-icon :name="isSelectAll ? 'e730' : 'e72f'" size="34" custom-prefix="iconfont"></u-icon>
					</view>
					<view class="sub-radio-text u-font-28">全选</view>
				</view>
				<view class="sub-price u-font-24">
					<view class="">合计：</view>
					<view class="price_main">
						<text class="u-font-24 sww-tp">￥</text>
						<text class="u-font-32 sww-tp">{{ $price(totalPrice) | priceFmt }}</text>
						<text class="u-font-24 sww-tp">{{ $price(totalPrice) | priceFmt(true) }}</text>
					</view>
				</view>

				<view class="deleall" v-if="selectIds[0]" @click="$onDeleteAll">批量删除</view>
				<view class="sub-btn" @click="$linkToOrder">立即支付({{ totalNum }})</view>
			</view>
		</sww-goods-action>
		<sww-login></sww-login>
	</view>
</template>
<script>
	import noStock from '@/components/noStock.vue';
	import {
		mapActions,
		mapState
	} from 'vuex';
	import {
		uniModal,
		uniNavigate
	} from '../../utils/uniPromise';
	import {
		pageShare
	} from '../../mixins/pageShare';
	export default {
		mixins: [pageShare],
		props: {
			actionPadding: {
				type: [String, Number],
				default: 104
			} // 支撑底部栏(如果是tabBar页，该值要与tabBar底部栏一直)
		},
		components: {
			noStock
		},
		data() {
			return {
				shareParams: {
					type: 1
				},
				selectIds: [],
				stockItem: {
					buyType: 'cart',
					prodId: '', //产品ID
					stockId: '', //产品规格ID
					num: 0, //产品规格购买数量
					cartId: '' //购物车ID
				},
				specVisible: false,
				showVip: false, // 是否允许显示并使用会员价格
				zfbNav: true,
			};
		},
		computed: {
			...mapState(['vuex_cart_list']),
			isSelect(id) {
				return id => {
					return this.selectIds.includes(id);
				};
			},
			isSelectAll() {
				let length = this.vuex_cart_list.length;
				return this.selectIds.length >= length;
			},
			totalPrice() {
				let set = new Set(this.selectIds);
				return this.vuex_cart_list
					.filter(item => set.has(item.pk_id))
					.reduce((sum, item) => {
						if (this.showVip && item.vip_price) {
							return sum + parseFloat(item.vip_price) * item.num;
						} else {
							return sum + parseFloat(item.price) * item.num;
						}
					}, 0);
			},
			totalNum() {
				let set = new Set(this.selectIds);
				return this.vuex_cart_list
					.filter(item => set.has(item.pk_id))
					.reduce((sum, item) => {
						return sum + item.num;
					}, 0);
			}
		},
		methods: {
			...mapActions(['loadUserCartList']),
			$onLoad() {},
			$onShow() {
				// #ifdef  MP-ALIPAY
				this.onZFBNav()
				// #endif 

				this.shareOnshow()
				this.$login('$onShow').then(() => {
					this.loadUserCartList();
					this.judgeVipPrice();
				});
			},
			$onHide() {
				// #ifdef  MP-ALIPAY
				this.selectIds = []
				// #endif 
			},

			// #ifdef  MP-ALIPAY
			onZFBNav() {
				//支付宝兼容
				//支付宝只能在tabbar页面可以隐藏顶上标题栏 但是其他页面隐藏不了，不是tabbar页面标题栏隐藏不了
				//从商品详情进入的购物车页面不是tabbar页面顶部栏是隐藏不了的，所以只能判断一下是tabbar就放出自定义导航栏
				let pages = getCurrentPages(); //获取当前的页面栈
				let row = pages[pages.length - 1] //当前页面
				if (row.$page.fullPath.indexOf('/pages/module-page') == -1) {
					this.zfbNav = false
				}
			},
			// #endif 

			// 判断是否允许显示并使用会员价格
			judgeVipPrice() {
				if (
					(this.vuex_user.type == 1 && this.vuex_user.level_name && this.vuex_user.level_name != '普通会员') ||
					(this.vuex_user.type == 2 && this.vuex_user.threelevel > 0) ||
					(this.vuex_user.type == 4 && this.vuex_user.threelevel > 0)
				) {
					this.showVip = true;
				}
			},
			$onReachBottom() {
				try {
					this.$refs.prodListRef.$loadMore();
				} catch (e) {}
			},
			onDetail(pk_id, is_online) {
				if (is_online == 1)
					this.$toProd({
						prodType: 1,
						pk_id
					});
			},
			// 修改数量
			$numChange(current, num, item) {
				this.$loading();
				this.$resPost('AddMallShoppingCart', {
						product_id: item.product_id,
						num,
						price: item.price,
						name: item.standard,
						stock_id: item.fk_attr_id
					})
					.then(() => {
						this.$hide();
						this.$u.vuex(`vuex_cart_list.${current.index}.num`, current.value);
					})
					.catch(() => {
						this.$hide();
						this.$u.vuex(`vuex_cart_list.${current.index}.num`, current.value - num);
					});
			},
			// 删除购物车
			$onDelete(item, index) {
				uniModal({
					content: '确认删除商品？'
				}).then(() => {
					this.$loading();
					this.$resPost('DeleteMyOrderCar', {
							pk_id: item.pk_id
						})
						.then(() => {
							this.$toast('删除成功', 'success');
							this.vuex_cart_list.splice(index, 1);
							this.$u.vuex('vuex_cart_list', this.vuex_cart_list);
							if (this.selectIds.includes(item.pk_id)) this.$onSelect(item.pk_id);
							this.$hide();
						})
						.catch(() => {
							this.$toast('删除失败');
						});
				});
			},

			// 批量删除购物车
			$onDeleteAll(item, index) {
				uniModal({
					content: '确认批量删除商品？'
				}).then(() => {
					this.$loading();

					let set = new Set(this.selectIds);
					let pk_id = this.vuex_cart_list
						.filter(item => set.has(item.pk_id))
						.reduce((sum, item) => {
							sum.push(item.pk_id);
							return sum;
						}, [])
						.join(',');

					this.$resPost('DeleteMyOrderCar', {
							pk_id
						})
						.then(() => {
							this.$toast('删除成功', 'success');
							this.loadUserCartList();
							this.selectIds = [];
						})
						.catch(() => {
							this.$toast('删除失败');
						});
				});
			},

			// 选择商品
			$onSelect(id, is_online) {
				// if (is_online == 1) {
				this.$u.throttle(() => {
					let set = new Set(this.selectIds);
					if (set.has(id)) {
						set.delete(id);
					} else {
						set.add(id);
					}
					this.selectIds = [...set];
				}, 200);
				return;
				// }
			},
			//全选、反选
			$onSelectAll() {
				this.$u.throttle(() => {
					if (this.isSelectAll) {
						this.selectIds = [];
					} else {
						this.selectIds = this.vuex_cart_list.map(item => item.pk_id);
					}
				}, 200);
			},
			// 选择规格
			$showSpec(item) {
				this.$u.debounce(
					() => {
						this.stockItem = {
							...this.stockItem,
							prodId: item.product_id,
							stockId: item.fk_attr_id,
							num: item.minimum >= item.max_num?item.max_num:item.minimum,
							cartId: item.pk_id
						};
						this.specVisible = true;
					},
					300,
					true
				);
			},
			// 跳转订单提交页
			$linkToOrder() {
				let $this = this;
				this.$u.debounce(
					() => {
						if (this.selectIds.length > 0) {
							let set = new Set(this.selectIds);
							let selectList = this.vuex_cart_list
								.filter(item => set.has(item.pk_id))
								.map(obj => {
									return {
										fk_supplier_id: obj.fk_supplier_id || 0,
										...obj
									};
								});
							if (selectList.length > 0) {
								let business_pro = false
								let judeg = selectList.find(el => {
									if (el.business_pro_id > 0) {
										business_pro = true
									}
									return el.is_online == 0
								});
								if (judeg) {
									this.$toast('所选商品中有无库存商品');
									return;
								}
								if ($this.showVip) {
									selectList.forEach((el, index) => {
										selectList[index].price = el.vip_price;
									});
								}
								let productObj = {
									type: 'cart',
									list: selectList
								}
								let url = '/package/product/local/order/index'
								if (business_pro) {
									url += '?business_pro=1'
								}
								// #ifdef MP-BAIDU || MP-ALIPAY || MP-TOUTIAO					
								this.$u.vuex('proShopPayList', productObj)
								this.$to(url)
								// #endif

								// #ifndef MP-ALIPAY || MP-BAIDU  || MP-TOUTIAO	
								uniNavigate(url, {
									$onSubmit: () => {
										this.selectIds = [];
									}
								}).then(res => {
									res.eventChannel.emit('acceptParams', {
										type: 'cart',
										list: selectList
									});
								});
								//#endif
							} else {
								this.selectIds = [];
								this.$toast('请选择商品');
							}
						} else {
							this.$toast('请选择商品');
						}
					},
					500,
					true
				);
			}
		},
		filters: {
			priceFmt(price, isPoint = false) {
				let [priceInt, pricePoint] = price.split('.');
				return isPoint ? (pricePoint ? '.' + pricePoint : '') : priceInt;
			}
		}
	};
</script>
<style lang="scss">
	page {
		background-color: $www-theme-bg;
	}
</style>
<style lang="scss" scoped>
	.index-box {
		width: 100%;
		height: auto !important;
		min-height: 100%;
		background-color: #f5f5f5;

		.data-list {
			width: 100%;

			.data-item {
				width: 100%;
				height: 260rpx;
				background-color: #ffffff;
				padding: 30rpx 24rpx 30rpx 0;
				position: relative;
				margin-bottom: 12rpx;
				display: flex;

				.data-radio {
					padding: 0 24rpx;
					display: flex;
					align-items: center;
					color: #999999;
				}

				.data-radio-act {
					color: var(--color);
				}

				.data-img {
					position: relative;
					width: 200rpx;
					height: 200rpx;
					margin-right: 20rpx;
					border-radius: 16rpx;
					box-shadow: 0 0 1rpx #ccc;
				}

				.data-right {
					flex: 1;
					height: 200rpx;
					overflow: hidden;
					display: flex;
					flex-direction: column;

					.title_box {
						display: flex;

						.data-title {
							flex: 1;
							overflow: hidden;
						}

						.data-del {
							margin-left: 6rpx;
							width: 40rpx;
							height: 40rpx;
							position: relative;
							top: 2rpx;
						}
					}

					.data-desc {
						display: flex;
						align-self: flex-start;
						background-color: #f5f5f5;
						padding: 8rpx 24rpx;
						max-width: 100%;
						border-radius: 8rpx;
						font-size: 22rpx;
						margin-top: 10rpx;
					}

					.data-bottom {
						margin-top: auto;
						display: flex;
						justify-content: space-between;
						align-items: flex-end;

						.data-price {
							color: var(--price);
						}
					}
				}
			}
		}

		.sub-bottom {
			width: 100%;
			height: 88rpx;
			background-color: #ffffff;
			display: flex;
			align-items: center;

			.sub-radio-wrap {
				margin-right: 20rpx;
				height: 100%;
				display: flex;
				align-items: center;

				.sub-radio {
					padding: 0 24rpx;
					color: #999999;
				}

				.sub-radio-act {
					color: var(--color);
				}
			}

			.sub-price {
				flex: 1;
				display: flex;
				align-items: center;

				.price_main {
					flex: 1;
					overflow: hidden;
				}
			}

			.sub-btn {
				width: 180rpx;
				height: 88rpx;
				background-color: var(--color);
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 26rpx;
				color: #ffffff;
			}
		}

		.no-data-box {
			width: 100%;
			height: 540rpx;
			padding-top: 150rpx;
			display: flex;
			flex-direction: column;
			align-items: center;

			.no-data-img {
				width: 250rpx;
				height: 142rpx;
				margin-bottom: 30rpx;
			}
		}

		.topic-data-box {
			width: 100%;

			.topic-data-title {
				width: 100%;
				height: 88rpx;
				padding: 0 24rpx;
				line-height: 88rpx;
				font-size: 32rpx;
				font-weight: bold;
			}
		}
	}

	.deleall {
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 26rpx;
		margin-left: 15rpx;
		background-color: rgba(0, 0, 0, 0.6);
		color: #fff;
		height: 100%;
		padding: 0 20rpx;
	}
</style>
